#!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
from Tkinter import Tk
from Tkinter import Toplevel
import ttk
import tkSimpleDialog
import tkMessageBox
from PIL import Image, ImageTk
from db import dbfile,dbmes
import win32con
import win32clipboard as wc

class MyDialog(Toplevel):
    def __init__(self, parent,p_x, p_y,swich,initText):
        # 弹窗界面
        Toplevel.__init__(self)
        self.title('设置用户信息')
        self.grab_set()
        self.userinfo = ['init']
        self.parent = parent
        # self.geometry("+%d+%d" % (parent.winfo_rootx() + 50, parent.winfo_rooty() + 50))

        # self.geometry("+%d+%d" % ( p_x+10, p_y+12 ))
        if swich=='rignt_key':
            self.right_key(p_x-15, p_y-4)
        elif swich=='dilog':
            self.setui(initText)
    def right_key(self,p_x, p_y):
        self.overrideredirect(True)
        row1 = Frame(self)
        row1.pack(fill='x')
        Button(row1, text="取消", command=lambda: self.right_even(1), width=20).pack(side=TOP)
        Button(row1, text="添加消息", command=lambda: self.right_even(2), width=20).pack(side=TOP)
        Button(row1, text="添加文件夹", command=lambda: self.right_even(3), width=20).pack(side=TOP)
        Button(row1, text="编辑", command=lambda: self.right_even(4), width=20).pack(side=TOP)
        Button(row1, text="删除", command=lambda: self.right_even(5), width=20).pack(side=TOP)

        self.geometry("+%d+%d" % (p_x + 10, p_y + 12))
    def right_even(self,w):
        self.destroy()
        if w==1:
            pass
        elif w==2:
            self.parent.mes_addfunc()
        elif w==3:
            self.parent.files_add(0)
        elif w==4:
            self.parent.filmes_edit()
        elif w==5:
            self.parent.filmes_del(1)
    def setui(self,initText):
        self.geometry("+%d+%d" % (self.parent.winfo_rootx() + 50, self.parent.winfo_rooty() + 50))
        row1 = Frame(self)

        self.Text = Text(row1,width=40,height=15)
        self.Text.insert(INSERT, initText)
        self.Text.pack(fill="x")
        row1.pack(fill='x')

        row2 = Frame(self)
        row2.pack()
        Button(row2, text="取消", command=self.cancel).pack(side=LEFT)
        Button(row2, text="确定", command=self.ok).pack(side=RIGHT)
    def ok(self):
        self.userinfo = self.Text.get("0.0", "end")  # 设置数据

        self.destroy()  # 销毁窗口
    def cancel(self):
        self.userinfo = ''  # 空！
        self.destroy()

class show(Tk):
    def __init__(self):
        Tk.__init__(self)

        # self.root = Tk()
        self.root = self
        self.root.geometry("+%d+%d" % (250, 150))
        self.root.title("snsc")
        self.root.geometry('300x450')
        self.root.resizable(width=False, height=True)
        self.root.iconbitmap("999.ico")

        self.items = ('',)

        self.fra_1 = Frame(self,bg='white')
        self.fra_2 = Frame(self,bg='white')
        self.fra_3 = Frame(self,bg='white')

        self.icon()
        Button(self.fra_1, text="快捷删除消息", command=lambda: self.quik_del_mes()).pack(side=RIGHT)
        Button(self.fra_1, text="设置", command=self.popwindow).pack(side=RIGHT)
        Button(self.fra_1, text="快捷添加消息", command=lambda: self.quik_add_mes(1)).pack(side=RIGHT)
        Button(self.fra_2, command=lambda: self.files_add(1), relief=GROOVE,anchor="center", image=self.root_add).pack(side=LEFT)

        Button(self.fra_2, command=lambda: self.files_add(0), relief=GROOVE,anchor="center", image=self.folder_add).pack(side=LEFT)
        Button(self.fra_2, command=self.mes_addfunc, relief=GROOVE,anchor="center", image=self.mes_add).pack(side=LEFT)
        Button(self.fra_2, command=self.filmes_edit, relief=GROOVE,anchor="center", image=self.mes_edit).pack(side=LEFT)
        Button(self.fra_2, command=lambda: self.filmes_del(1), relief=GROOVE, anchor="center", image=self.mes_remove).pack(side=LEFT)
        Button(self.fra_2, command=self.fresh, relief=GROOVE,anchor="center", image=self.refresh).pack(side=LEFT)

        self.menu()
        self.fra_1.pack(fill=X, expand=0)
        self.fra_2.pack(fill=X, expand=0)
        self.fra_3.pack(fill=BOTH, expand=1)

        self.tree = ttk.Treeview(self.fra_3)
        self.tree["selectmode"] = "extended"
        self.tree["show"] = ["tree", "headings"]
        self.tree.bind("<Double-1>", self.hello)
        self.tree.bind("<<TreeviewSelect>>", self.FocusCli)
        self.tree.bind("<Button-3>", self.rignt_key)

        self.filjs = []
        self.fresh()
    #刷新列表
    def fresh(self):
        self.mes_list = {}
        self.Folder_list = {}
        for i,item in enumerate(self.filjs):
            if item[2]==-1:
                self.tree.delete((item[0],))
        self.fildb = dbfile()
        self.mesdb = dbmes()
        self.filjsOld = self.fildb.search().fetchall()
        self.files_len = self.fildb.search_maxid()[0] or 0
        # print self.filjsOld
        self.filjs = []
        for i, item in enumerate(self.filjsOld):
            self.filjs.append( list( item ) )
        # self.filjs = self.filjsOld
        self.mesjsOld = self.mesdb.search().fetchall()
        self.mes_len = self.mesdb.search_maxid()[0] or 0
        self.mesjs = self.mesjsOld
        self.mes_list = {}
        self.Folder_list = {}
        self.creatree()

    #添加文件夹
    def files_add(self,root):
        # , pid, name, sid
        name = tkSimpleDialog.askstring('名称', 'string', initialvalue='new') or 'new'
        pid = self.items[0]
        if self.iscli_files():
            pmd = self.Folder_list[int(pid)]
        else:
            pid = -1
            pmd = ''
        if root==1:
            pid = -1
            pmd = ''
        self.files_len += 1
        sid = self.files_len
        self.fildb.inser(pid, name, sid)
        self.Folder_list[int(sid)] = self.tree.insert(pmd, "end", sid, text=name.split('\n')[0], image=self.folder)

    # 添加消息
    def mes_addfunc(self):
        # , pid, content, sid
        id = self.items[0]
        self.mes_len += 1
        item_id = self.mes_len
        sid = self.mes_len
        if self.iscli_mes():
            pid = self.tree.parent(id)
            # target_sid =  self.tree.item(id)
            target_sid = self.tree.item(id)['values'][0]
            sid = target_sid + 1
            self.mesdb.addsid(target_sid)  # 当前顺序向后增加1
            # print self.tree.item( self.tree.next(id) )['values']
            # 1.获取当前item sid 和下一个item sid
        elif self.iscli_files():
            pid = id
        else:
            # print '请选择文件夹'
            tkMessageBox.showwarning('提示', '请选择文件夹！')
            return
        content = self.get_info(0, 0, 'dilog', '') or 'test'
        currenselect = "%s%s" % ("m", item_id)

        self.mes_list["m" + str(item_id)] = self.tree.insert(pid, "end", currenselect, text=content.split('\n')[0],
                                                             values=sid, image=self.mes)
        self.tree.selection_set(currenselect)
        self.mesdb.inser(pid, content, sid)
        # currenselect = 'm22'
        self.tree.selection_set(currenselect)
        self.items = (currenselect,)
        while 1:
            pid = self.tree.parent(currenselect)
            if pid:
                self.tree.item(pid, open=1)
                currenselect = pid
            else:
                break
        return

    # 编辑文件夹或消息
    def filmes_edit(self):
        # , id, name
        id = self.items[0]
        if id=='':
            tkMessageBox.showwarning('提示', '请选择文件夹！')
        elif self.iscli_files():
            # initi = self.tree.item(id)["text"]
            print '文件'
            for it in self.filjs:
                if it[0] == int(id):
                    print it, '==', id
                    initi = it[1]
                    break
            initi = initi or 'new'
            name = tkSimpleDialog.askstring('名称', 'str', initialvalue=initi)
            print name
            if not name:
                return
            self.fildb.update(id, name)
            name = '%s%s%s%s' % (name.split('\n')[0], "(", len( self.tree.get_children(id) ), ")")
            self.tree.item(id, text=name)
        elif self.iscli_mes():
            print '消息'
            for it in self.mesjs:
                if it[0] == int(id[1:]):
                    print it, '==', id
                    initText = it[1]
                    break
            initText = initText or ' '
            content = self.get_info(0, 0, 'dilog', initText)
            if not bool(content.encode('utf-8')):
                return
            # content = tkSimpleDialog.askstring('内容', 'str', initialvalue=initi) or initi
            self.tree.item(id, text=content.split('\n')[0])
            id = id[1:]
            self.mesdb.update(id, content)
        return
    # 删除文件或文件夹
    def filmes_del(self,wh):
        id = self.items[0]
        print id
        if id=='':
            tkMessageBox.showwarning('提示', '请选择文件夹或消息！')
        elif self.iscli_files():
            if len(self.tree.get_children(id))>0:
                tkMessageBox.showwarning('提示', '只能删除空文件夹！')
                return
            issure = tkMessageBox.showwarning('提示', '确定删除这个文件夹吗？')
            if issure:
                self.items = ('',)

                self.fildb.delt(id)
                self.tree.delete((id,))
        elif self.iscli_mes():
            if wh==1:
                isure = tkMessageBox.showwarning('提示', '确定删除消息吗？')
            else:
                isure = True
            if isure:
                next_id = self.tree.next(id)
                if next_id:
                    self.tree.selection_set(next_id)
                    print next_id
                else:
                    self.items = ('',)
                # print self.tree.focus_set()
                print self.tree.focus()
                self.tree.delete((id,))
                id = id[1:]
                self.mesdb.delt(id)
        return
    #快捷删除消息
    def quik_del_mes(self):
        self.filmes_del(2)
    def iscli_mes(self):
        id = self.items[0]
        if 'm' in id:
            return True
        else:
            return False
    def iscli_files(self):
        id = self.items[0]
        if id == '' or ('m' in id):
            return False
        return True
    def hello(self,aa):
        # print "hello 11"
        pass
    def rignt_key(self,even):
        # print "hello 11"
        # print even.x,'=',even.y
        # print even.x_root, '=', even.y_root
        p_x,p_y = even.x_root,even.y_root
        self.get_info(p_x, p_y, 'rignt_key',1)
    def popwindow(self):
        res = self.get_info(0, 0, 'dilog',1)
        # print res
    #快速添加消息
    def quik_add_mes(self,aa):
        # item = self.tree.focus()
        #获取剪切板内容
        wc.OpenClipboard()
        copy_text = wc.GetClipboardData(win32con.CF_TEXT)
        # print copy_text.decode('gbk')
        if copy_text == '':
            wc.CloseClipboard()
            return
        # wc.SetClipboardData(win32con.CF_TEXT, '')
        wc.CloseClipboard()

        # id = item
        self.mes_len += 1
        sid = self.mes_len
        item_id = self.mes_len
        id = self.items[0]
        # print id
        if self.iscli_mes():
            pid = self.tree.parent(id)
            target_sid = self.tree.item(id)['values'][0]
            # print target_sid
            sid = target_sid + 1
            self.mesdb.addsid(target_sid)  # 当前顺序向后增加1
        elif self.iscli_files():
            pid = id

        else:
            tkMessageBox.showwarning('提示', '请选择文件夹！')
            return
        content = copy_text.decode('gbk')
        currenselect = '%s%s' % ('m', item_id)
        self.mes_list[currenselect] = self.tree.insert(pid, "end", currenselect, text=content.split('\n')[0], values=sid, image=self.mes)

        self.mesdb.inser(pid, content, sid)
        self.tree.selection_set(currenselect)
        self.items = (currenselect,)

        self.tree.selection_set(currenselect)
        while 1:
            pid = self.tree.parent(currenselect)
            if pid:
                self.tree.item(pid, open=1)
                currenselect = pid
            else:
                break

        return

        # print item
        # if self.iscli_files():
        #     return
        # for it in self.mesjs:
        #     if it[0] == int(item[1:]):
        #         initText = it[1]
        #         break
        # print initText
        # if item.isdigit():
        #     pass
            # print self.tree.get_children(item)

    def FocusCli(self, a):
        item = self.tree.focus()#获取一个选中
        self.items = self.tree.selection()#获取所有选中
        open = self.tree.item(item)["open"]
        # print self.tree.item(item)
        self.tree.item(item, open=not open)
        # print self.tree.selection()

    def get_info(self,p_x, p_y, swich,initText):
        inputDialog = MyDialog(self,p_x, p_y,swich,initText)
        self.wait_window(inputDialog)  # 这一句很重要！！！
        return inputDialog.userinfo
    # 渲染设置列表
    def menu(self):
        self.menubar = Menu(self.root)
        self.menubar.add_command(label="板块", command=self.hello)
        self.files = Menu(self.menubar, tearoff=0)
        self.files.add_command(label="设置", command=self.hello)
        self.files.add_command(label="数据0", command=self.hello)
        self.files.add_command(label="数据1", command=self.hello)
        self.menubar.add_command(label="数据2", command=self.hello)
        self.menubar.add_cascade(label='板块2', menu=self.files)
        self.root['menu'] = self.menubar
    # 渲染树结构
    def creatree(self):
        for i,item in enumerate(self.filjs):
            if item[2]==-1:
                self.Folder_list[item[0]] = self.tree.insert("", "end", item[0],text=item[1].split('\n')[0],values=item[3], image=self.folder)
                self.blfile(item[0], self.Folder_list[item[0]])
                self.blmes(item[0], self.Folder_list[item[0]])
        self.tree.pack(fill=BOTH, expand=1)
    # 文件夹遍历
    def blfile(self,pid,pmd):
        for i, item in enumerate(self.filjs):
            # self.filjs[i] = list(self.filjs[i])
            if item[2]==pid:
                self.Folder_list[item[0]] = self.tree.insert(pmd, "end", item[0], text=item[1].split('\n')[0],values=item[3], image=self.folder)
                self.blfile(item[0], self.Folder_list[item[0]])
                self.blmes(item[0], self.Folder_list[item[0]])
    # 消息遍历
    def blmes(self, pid, pmd):
        ordli = 0
        for j, item in enumerate(self.mesjs):
            self.mesjs[j] = list(self.mesjs[j])
            if item[2]==pid:
                ordli += 1
                ordlitext = '%s%s%s' % (ordli, '. ', item[1].split('\n')[0])
                self.mes_list["m"+str(item[0])] = self.tree.insert(pmd, "end", "m"+str(item[0]), text=ordlitext, values=item[3], image=self.mes)
        initi = self.tree.item(pid)["text"]
        name = '%s%s%s%s' % (initi, "(", ordli, ")")
        self.tree.item(pid, text=name )
    #小图标
    def icon(self):
        self.refresh = ImageTk.PhotoImage(Image.open('icon/refresh.png'))
        self.root_add = ImageTk.PhotoImage(Image.open('icon/root_add.png'))
        self.folder = ImageTk.PhotoImage(Image.open('icon/folder.png'))
        self.folder_add = ImageTk.PhotoImage(Image.open('icon/folder_add.png'))
        self.folder_edit = ImageTk.PhotoImage(Image.open('icon/folder_edit.png'))
        self.folder_remove = ImageTk.PhotoImage(Image.open('icon/folder_remove.png'))
        self.mes = ImageTk.PhotoImage(Image.open('icon/mes.png'))
        self.mes_add = ImageTk.PhotoImage(Image.open('icon/mes_add.png'))
        self.mes_edit = ImageTk.PhotoImage(Image.open('icon/mes_edit.png'))
        self.mes_remove = ImageTk.PhotoImage(Image.open('icon/mes_remove.png'))

if __name__ == "__main__":
    app = show()
    app.mainloop()